gpt4 book ai didi

c++ - 静态非模板成员函数与静态模板成员函数

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

#include <iostream>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
using namespace std;

struct TestClass
{
static void Create(boost::shared_ptr<const int> shp)
{
cout << "TestClass::Create: " << *shp << endl;
}


template <typename T>
static void CreateT(boost::shared_ptr<const T> shp)
{
cout << "TestClass::CreateT: " << *shp << endl;
}


};

int main()
{
boost::shared_ptr<int> shpInt = boost::make_shared<int>(10);
boost::shared_ptr<const int> shpConstInt = shpInt;

TestClass::Create( shpInt ); // OK
TestClass::Create( shpConstInt ); // OK

//error C2664: 'void TestClass::CreateT<int>(boost::shared_ptr<T>)' :
//cannot convert parameter 1 from 'boost::shared_ptr<T>' to 'boost::shared_ptr<T>'
TestClass::CreateT( shpInt ); // ERROR

TestClass::CreateT( shpConstInt ); // OK

// workaround
boost::shared_ptr<const int> shpConstInt2 = shpInt;
TestClass::CreateT( shpConstInt2 ); // OK

return 0;
}

问题> 为什么 TestClass::CreateT( shpInt )TestClass::Create( shpInt ) 时不起作用工作正常。是不是因为TestClass::CreateT是一个仅支持静态绑定(bind)的模板函数,它不能从boost::shared_ptr<T> 进行自动转换。至 boost::shared_ptr<const T>

谢谢

最佳答案

非模板版本可以工作,因为不涉及类型推导。编译器知道他必须转换的类型类型(以防它们不是相同的类型),并简单地检查是否存在可能的转换。 p>

对于模板化版本,这不再是真的。他首先必须推导出模板。

对于 boost::shared_ptr<const int>boost::shared_ptr<const T>这很简单,因为找到了完美匹配:Tint (因此不需要也不涉及转换)。

来自 boost::shared_ptr<int> 的比赛至 boost::shared_ptr<const T>没有T这将产生相同的两种类型。所以问题是‘什么是T ?' 对你来说这可能是显而易见的(你仍然会错),但编译器无法推断出 T因为它不是完美的匹配。下一个最好的事情是在两种类型之间进行转换,但这意味着要尝试 T 的所有可能性。 (它们是无限的)并查看哪个产生可转换类型。例如。 T = long -> boost::shared_ptr<const long>可以转换为 boost::shared_ptr<int>T = Foo (其中 Foo 是用户定义的类) -> boost::shared_ptr<const Foo>可以转换为 boost::shared_ptr<int> .所以他没有办法推断T .我知道这不是一个学术答案,更了解该标准的人可以引用该标准中的类型推导规则,但最终这些规则在某种程度上是由上述解释插入的。

关于c++ - 静态非模板成员函数与静态模板成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23500056/

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