linux&c++ R&D

programing is a pleasure!

How to limit instantialization?

Title: How to limit instantialization?
For a template class:
template <typename T>
struct X
{
    static void f(){...}

};

Is there any way to prevent this class from being instantialized for
different T?
e.g:
X<int>::f();
X<int>::f() //ok
///////////////////////////////////////////////
X<int>::f();
X<double>::f() //compiling error
Instantialization may be found in different source files, and X<T> may
not have to have any instance.
I tried some methods, but failed to prevent it in compile time.
Can anyone help me out?
(1)
On 12 Mrz., 15:19, "shifan3" <shifan1234...@163.com> wrote:
SFINAE is your friend. Your main task is to define/specialize
your traits class MyTraits, which specifies enablement, properly.
In this case I have used explicit specializiation for it, maybe you
need partial specialization:
template <bool Enable, typename T = void>
struct EnableIf {
   typedef T Type;

};
template <typename T>
struct EnableIf<false, T> {

};
template <typename T>
struct MyTraits {
   static const bool value = false; // Default case: Disable

};
template <>
struct MyTraits<int> {
   static const bool value = true;

};
template <typename T>
struct X
{
     static typename
     EnableIf<MyTraits<T>::value>::Type f(){...}

};
int main() {
   X<int>::f(); // OK
   X<double>::f(); // Fails

}
Greetings from Bremen,
Daniel Krügler

(2)
template <typename T>
struct X
{
    static void f(){...}

};
template<> struct X<double>;
or, if you don't want the incomplete type,
template<>
struct X<double>
{

};

 

 

posted on 2007-04-30 16:44 丑石 阅读(381) 评论(0)  编辑 收藏 引用 所属分类: C++ problem and solution


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


My Links

Blog Stats

News

常用链接

留言簿(1)

随笔分类(13)

随笔档案(17)

文章档案(1)

相册

收藏夹(1)

Friends' blog

useful sites

搜索

积分与排名

最新评论

阅读排行榜

评论排行榜