C++ 可变参数模板特化(和 static_assert)
C++ variadic template specialization (and static_assert)
是否可以专门化此模板声明:
template <class TYPE, class... ARGS> TYPE Foo(ARGS... args) {
static_assert(false);
}
我尝试了一些方法,例如:
template <> int Foo<int>(float args) {
return 42;
}
...但是当我尝试这样使用它时,我总是会遇到静态断言:
auto value = Foo<int>(1.5f);
正确的语法是什么?
您不得编写仅在未实例化时才有效的模板。这与标准中的以下规则相冲突:
If no valid specialization can
be generated for a template, and that template is not instantiated, the template is ill-formed, no diagnostic
required.
另一方面,如果您在 body 中有一些东西就好了,例如
static_assert(sizeof(TYPE) != sizeof(int));
在这种情况下,模板是有效的,并且您的代码将编译,因为实际上将使用显式特化而不是主模板。参见 http://coliru.stacked-crooked.com/a/238b979fd10c62c0
您的静态断言不依赖于模板,因此它将始终触发。使用像
这样的东西
template <class TYPE, class... ARGS> TYPE Foo(ARGS... args) {
static_assert(sizeof(TYPE) != sizeof(TYPE));
}
作为状态,false
不依赖于模板,因此 static_assert
应该触发。
您可以在您的情况下使用 = delete
:
template <class TYPE, class... ARGS> TYPE Foo(ARGS... args) = delete;
template <> int Foo(float) {return 42;}
是否可以专门化此模板声明:
template <class TYPE, class... ARGS> TYPE Foo(ARGS... args) {
static_assert(false);
}
我尝试了一些方法,例如:
template <> int Foo<int>(float args) {
return 42;
}
...但是当我尝试这样使用它时,我总是会遇到静态断言:
auto value = Foo<int>(1.5f);
正确的语法是什么?
您不得编写仅在未实例化时才有效的模板。这与标准中的以下规则相冲突:
If no valid specialization can be generated for a template, and that template is not instantiated, the template is ill-formed, no diagnostic required.
另一方面,如果您在 body 中有一些东西就好了,例如
static_assert(sizeof(TYPE) != sizeof(int));
在这种情况下,模板是有效的,并且您的代码将编译,因为实际上将使用显式特化而不是主模板。参见 http://coliru.stacked-crooked.com/a/238b979fd10c62c0
您的静态断言不依赖于模板,因此它将始终触发。使用像
这样的东西template <class TYPE, class... ARGS> TYPE Foo(ARGS... args) {
static_assert(sizeof(TYPE) != sizeof(TYPE));
}
作为状态,false
不依赖于模板,因此 static_assert
应该触发。
您可以在您的情况下使用 = delete
:
template <class TYPE, class... ARGS> TYPE Foo(ARGS... args) = delete;
template <> int Foo(float) {return 42;}