【发布时间】:2012-04-16 19:41:48
【问题描述】:
假设我有这些模板别名:
enum class enabler {};
template <typename T>
using EnableIf = typename std::enable_if<T::value, enabler>::type;
template <typename T>
using DisableIf = typename std::enable_if<!T::value, enabler>::type;
我可以在 GCC 中执行以下操作:
#include <iostream>
template <typename T, EnableIf<std::is_polymorphic<T>> = {}>
void f(T) { std::cout << "is polymorphic\n"; }
template <typename T, DisableIf<std::is_polymorphic<T>> = {}>
void f(T) { std::cout << "is not polymorphic\n"; }
struct foo { virtual void g() {} };
int main() {
f(foo {});
f(int {});
}
打印出来:
是多态的
不是多态的
这符合我的期望。
使用 clang 代码无法编译。它会产生以下错误消息。
test.cpp:11:58: error: expected expression
template <typename T, EnableIf<std::is_polymorphic<T>> = {}>
^
test.cpp:14:59: error: expected expression
template <typename T, DisableIf<std::is_polymorphic<T>> = {}>
^
test.cpp:20:3: error: no matching function for call to 'f'
f(foo {});
^
test.cpp:12:6: note: candidate template ignored: couldn't infer template argument ''
void f(T) { std::cout << "is polymorphic\n"; }
^
test.cpp:15:6: note: candidate template ignored: couldn't infer template argument ''
void f(T) { std::cout << "is not polymorphic\n"; }
^
test.cpp:21:3: error: no matching function for call to 'f'
f(int {});
^
test.cpp:12:6: note: candidate template ignored: couldn't infer template argument ''
void f(T) { std::cout << "is polymorphic\n"; }
^
test.cpp:15:6: note: candidate template ignored: couldn't infer template argument ''
void f(T) { std::cout << "is not polymorphic\n"; }
^
4 errors generated.
它应该编译吗?这两个编译器哪个有问题?
【问题讨论】:
-
哎呀,我觉得很傻。我觉得这与模板别名无关,因此标题可能具有误导性:S 抱歉,如果情况属实,我会调查一下并修正标题。
-
DisableIf<std::is_polymorphic<T>> = {}是合法的初始化列表初始化吗?结构可以是模板值参数吗? -
@jpalecek 不,结构不能。这就是我使用枚举的原因:)
-
如果我不使用别名而只是手动“内联”它们,Clang 会发出类似的错误消息,因此我修复了标题。
-
@jpalecek 这是枚举的name。它指的是
enum {}有效,但enum class {}无效。在这里完全不相关。
标签: c++ templates c++11 sfinae template-aliases