c++ - 在这种情况下, “typename…”是什么意思?

标签 c++ templates typename

我在cppreference.com中找到了一些我不理解的代码。
这是链接: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;的类型被推导为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();仅接受嵌套类型为typename TT::foo。例如,
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

关于c++ - 在这种情况下, “typename…”是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59575431/

相关文章:

带有 'const' 的 C++ 模板

c++ - 在泛型编程中选择类型参数

php - Apache 不想在 FIFO(管道)中 fopen 或 fwrite

C++:隐式转换

c++ - 基于其他模板定义从模板类到原始类型的隐式转换

c++ - 表达式模板的核心功能 : assignment operator sub-template type?

c++ - 为什么 C++20 模板 lambda 使用 typename 关键字?

c++ - 不在模板中声明类型名称的用例是什么?

c++ - 哪些 VertexList 类型对 depth_first_search 有效

c++ - 模板模板参数有哪些用途?