Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;模板#if和typeid以获取对象 类持有者 { 公众: 模板 不明白 { #if(typeid(T)=typeid(object1)){ 返回obj1; } #elif(typeid(T)=typeid(object2)){ 返回obj2; } //#其他{ //return nullptr;//对不起,我弄错了。忽略它。 // } #恩迪夫 } 私人: 对象1 obj1; 对象2 obj2; }_C++_Oop_C++11_Templates - Fatal编程技术网

C++ C++;模板#if和typeid以获取对象 类持有者 { 公众: 模板 不明白 { #if(typeid(T)=typeid(object1)){ 返回obj1; } #elif(typeid(T)=typeid(object2)){ 返回obj2; } //#其他{ //return nullptr;//对不起,我弄错了。忽略它。 // } #恩迪夫 } 私人: 对象1 obj1; 对象2 obj2; }

C++ C++;模板#if和typeid以获取对象 类持有者 { 公众: 模板 不明白 { #if(typeid(T)=typeid(object1)){ 返回obj1; } #elif(typeid(T)=typeid(object2)){ 返回obj2; } //#其他{ //return nullptr;//对不起,我弄错了。忽略它。 // } #恩迪夫 } 私人: 对象1 obj1; 对象2 obj2; },c++,oop,c++11,templates,C++,Oop,C++11,Templates,想要通过模板获得一个对象,但它不起作用。为什么以及如何修改它。? 我知道 像这样使用它: class holder { public: template<class T> T get() { #if (typeid(T) == typeid(object1)){ return obj1; } #elif (typeid(T) == typeid(object2)){

想要通过模板获得一个对象,但它不起作用。为什么以及如何修改它。? 我知道 像这样使用它:

class holder
{
public:
     template<class T>
     T get()
     {
        #if (typeid(T) == typeid(object1)){
          return obj1;
        }
        #elif (typeid(T) == typeid(object2)){
          return obj2;
        }
       // #else{
          // return nullptr; // sory my mistake. ignore it.
       // }
       #endif
    }

private:
    object1 obj1;
    object2 obj2;
}
持有人a;
object1 obj1=a.get();

将宏与模板一起使用不是一个好主意。你可以用这个。e、 g

holder a;
object1 obj1 = a.get<object1>();

在编译器和类型系统意识到模板之前,预处理器已经完成了它的运行。你试图达到你想要的行为的方式是不可能的。当你关心类型时,甚至忘记预处理器的存在。
holder
对象的应用程序是什么?您正在尝试在运行时切换类型吗?您最好为每种类型的对象创建一个getter,例如
object1&getObj1()
object2&getObj2()请记住,在这种情况下不会有默认的
nullptr
版本,因为您返回的是类型为T的对象。很可能您希望函数签名为
T&get()
,但请记住,在使用引用时,您需要将
holder
对象保持在作用域内。@Matt-我认为OP的
nullptr
方法是处理非法使用的一个难题。硬错误更可取。顺便说一句,如果你
删除
主模板特化,错误弹出的速度会比链接时间快得多。对不起,我搞错了。不是空PTR。我的意图是共享ptr。这是伪代码。@user2163635好吧,取决于您的意图,您可以选择在BTW部分中显示的任何一种方式。刚才,我测试了它。但它是2005年LNK的编辑者。Aready已定义。因为在头文件中定义了模板方法。如何解决?谢谢
class holder
{
public:
     template<class T>
     T get() {
         return {};
     }
private:
    object1 obj1;
    object2 obj2;
};

template<>
object1 holder::get<object1>() { return obj1; }
template<>
object2 holder::get<object2>() { return obj2; }
class holder
{
public:
     template<class T>
     T get() {
         if constexpr (std::is_same_v<T, object1>) 
             return obj1;
         else if constexpr (std::is_same_v<T, object2>) 
             return obj2;
         else
             return {};
     }
private:
    object1 obj1;
    object2 obj2;
};