"typename..." 在这种情况下是什么意思?
What does "typename..." mean in this context?
我在 cppreference.com 中发现了一些我不理解的代码。
这里是link:Type Alias。它在谈论 dependent template-id
我不明白。
这是代码:
//When the result of specializing an alias template is a dependent template-id,
//subsequent substitutions apply to that template-id:
template<typename...>
using void_t = void;
template<typename T>
void_t<typename T::foo> f();
f<int>(); // error, int does not have a nested type foo
当我在 VS 2019 上将鼠标悬停在它上面时,它说
void_t<<
未命名>...>
谁能给我解释一下这个未命名的类型名有什么用?
这是一个没有名字的模板包,因为它没有被使用。您可以传递任何类型,结果将是相同的。
template<typename...>
using void_t = void;
它允许您将模板参数传递给它,它只会吃掉所有参数,从而产生相同的类型。对SFINAE有用
让我试着解释一下,
类型推导为 void
的表达式 template<typename...> using void_t = void;
,与传递的模板参数无关。
例如,
template<typename...>
using void_t = void;
template <typename T>
void_t<T> fun1() {
std::cout << "fun1 called" << std::endl;
}
int main() {
fun1<int>(); //fun1 called
fun1<float>(); //fun1 called
}
为了扩展相同的内容,template<typename T>void_t<typename T::foo> f();
只接受具有嵌套类型 T::foo
的 typename T
。例如,
template<typename...>
using void_t = void;
template<typename T>
void_t<typename T::foo> f() {}
struct bar
{
typedef int foo;
};
int main() {
f<bar>(); //Valid expression as bar::foo is nested type of bar
f<int>(); //Error because `int::foo`is not a nested type of `int`.
}
有关详细信息,请参阅 Substitution failure is not an error
我在 cppreference.com 中发现了一些我不理解的代码。
这里是link:Type Alias。它在谈论 dependent template-id
我不明白。
这是代码:
//When the result of specializing an alias template is a dependent template-id,
//subsequent substitutions apply to that template-id:
template<typename...>
using void_t = void;
template<typename T>
void_t<typename T::foo> f();
f<int>(); // error, int does not have a nested type foo
当我在 VS 2019 上将鼠标悬停在它上面时,它说
void_t<<
未命名>...>
谁能给我解释一下这个未命名的类型名有什么用?
这是一个没有名字的模板包,因为它没有被使用。您可以传递任何类型,结果将是相同的。
template<typename...>
using void_t = void;
它允许您将模板参数传递给它,它只会吃掉所有参数,从而产生相同的类型。对SFINAE有用
让我试着解释一下,
类型推导为 void
的表达式 template<typename...> using void_t = void;
,与传递的模板参数无关。
例如,
template<typename...>
using void_t = void;
template <typename T>
void_t<T> fun1() {
std::cout << "fun1 called" << std::endl;
}
int main() {
fun1<int>(); //fun1 called
fun1<float>(); //fun1 called
}
为了扩展相同的内容,template<typename T>void_t<typename T::foo> f();
只接受具有嵌套类型 T::foo
的 typename T
。例如,
template<typename...>
using void_t = void;
template<typename T>
void_t<typename T::foo> f() {}
struct bar
{
typedef int foo;
};
int main() {
f<bar>(); //Valid expression as bar::foo is nested type of bar
f<int>(); //Error because `int::foo`is not a nested type of `int`.
}
有关详细信息,请参阅 Substitution failure is not an error