ere*_*eOn 38 c++ templates boost compilation
我有一个模板化class(称之为Foo),它有几个特化.如果有人试图使用非专业版本,我希望编译失败Foo.
这是我实际拥有的:
template <typename Type>
class Foo
{
Foo() { cannot_instantiate_an_unspecialized_Foo(); }
// This method is NEVER defined to prevent linking.
// Its name was chosen to provide a clear explanation why the compilation failed.
void cannot_instantiate_an_unspecialized_Foo();
};
template <>
class Foo<int>
{ };
template <>
class Foo<double>
{ };
Run Code Online (Sandbox Code Playgroud)
以便:
int main()
{
Foo<int> foo;
}
Run Code Online (Sandbox Code Playgroud)
适用时:
int main()
{
Foo<char> foo;
}
Run Code Online (Sandbox Code Playgroud)
才不是.
显然,编译器链只在链接过程发生时才会抱怨.但有没有办法让它在之前抱怨?
我可以用boost.
Seb*_*fel 43
只是不要定义类:
template <typename Type>
class Foo;
template <>
class Foo<int> { };
int main(int argc, char *argv[])
{
Foo<int> f; // Fine, Foo<int> exists
Foo<char> fc; // Error, incomplete type
return 0;
}
Run Code Online (Sandbox Code Playgroud)
为什么这样做?仅仅因为没有任何通用模板.声明,是的,但没有定义.
Ker*_* SB 22
您无法定义基本情况:
template <typename> class Foo; // no definition!
template <> class Foo<int> { /* ... */ }; // Foo<int> is OK
Run Code Online (Sandbox Code Playgroud)
Luc*_*ton 17
C++ 0x的一个技巧(也可用于C++ 03 static_assert仿真,但错误消息不一定比保留主模板未定义更好):
template<typename T>
struct dependent_false: std::false_type {};
template<typename Type>
struct Foo {
static_assert( dependent_false<Type>::value
, "Only specializations of Foo may be used" );
};
Run Code Online (Sandbox Code Playgroud)
断言仅在Foo使用主模板实例化时触发.使用static_assert( false, ... )会一直触发断言.
| 归档时间: |
|
| 查看次数: |
5090 次 |
| 最近记录: |