gpt4 book ai didi

c++ - 模板模板参数的类型推导(C++)

转载 作者:行者123 更新时间:2023-11-30 05:07:25 26 4
gpt4 key购买 nike

使用下面的代码我遇到了编译器错误:

type/value mismatch at argument 1 in template parameter list for 'template<class _Tp> class std::shared_ptr'
std::shared_ptr<T> shared_pointer;
^
../test/main.cpp:16:22: note: expected a type, got 'T'

不明白为什么T未正确推导 shared_pointer

template<typename K>
class Bar{
K k;
};

template<template<typename> class T>
class Foo{
public:
std::shared_ptr<T> shared_pointer;
};


int main(void)
{
Foo<Bar<std::string>> foo;
}

更新:另一个例子:

template<typename TObject, template<TObject> class TBuffer>
class BaseGrabber {

public:
virtual void run(std::shared_ptr<TBuffer>){};
};

当有人写类似的东西时,我想强制编译器出错

BaseGrabber<int, Bar<long>> grabber;

所以 Bar从未专门研究与第一个不同的类型BaseGrabber模板参数。

最佳答案

问题 1:

[I] can't figure out why T is not properly deduced for shared_pointer?

template<template<typename> class T>
class Foo{
public:
std::shared_ptr<T> shared_pointer;
};

答案: T不能推导出 shared_ptr因为T是一个模板化类型,你没有给它任何模板参数。只需将其减少到 class T它会起作用:

template<class T>
class Foo{
public:
std::shared_ptr<T> shared_pointer;
};

问题 2:

I want to force compiler error when someone write something like:
BaseGrabber<int, Bar<long>> grabber;

答案:我们将为 BaseGrabber 编写一个空的主要特化,然后在第二个参数使用与第一个参数相同的模板参数类型时专门化它:

template<class T, class U>
class BaseGrabber{
static_assert(sizeof(T) == 0, "Template argument is not correct");
};

template<class T, template<class> class U>
class BaseGrabber<T, U<T>> {
public:
virtual void run(std::shared_ptr<T>){};
}

这样测试:

int main()
{
Foo<Bar<std::string>> foo;
//BaseGrabber<int, Bar<long>> grabber; // compiler error
BaseGrabber<int, Bar<int>> grabber;
}

Live Demo

关于c++ - 模板模板参数的类型推导(C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47438130/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com