Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/142.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++_Generics_Inheritance_Type Erasure - Fatal编程技术网

C++ 虚模板成员函数

C++ 虚模板成员函数,c++,generics,inheritance,type-erasure,C++,Generics,Inheritance,Type Erasure,我知道不能有一个虚拟模板成员函数,但我希望有类似的工作 考虑以下伪代码: struct abstract { template<typename T> virtual T get() const = 0; }; using abstract_pointer = std::shared_ptr<abstract>; struct concrete_int : public abstract { template<> int g

我知道不能有一个虚拟模板成员函数,但我希望有类似的工作

考虑以下伪代码:

struct abstract
{
    template<typename T>
    virtual T get() const = 0;
};

using abstract_pointer = std::shared_ptr<abstract>;

struct concrete_int : public abstract
{
    template<>
    int get() const { return 123; }
};

struct concrete_string : public abstract
{
    template<>
    std::string get() const { return "abc"; }
};

abstract_pointer factory()
{
    // Some logic here to decide what concrete type to return
    return ...;
}

void print_value(abstract_pointer p)
{
    // Will print either 123 or "abc"
    std::cout << "p = " << p->get() << '\n';
}

int main()
{
    abstract_pointer p = factory();

    print_value(p);
}
struct抽象
{
模板
虚拟T get()常量=0;
};
使用抽象指针=std::shared\u ptr;
结构具体内容:公共摘要
{
模板
int get()常量{return 123;}
};
结构具体字符串:公共摘要
{
模板
std::string get()常量{return“abc”;}
};
抽象指针工厂()
{
//这里有一些逻辑来决定返回什么具体类型
返回。。。;
}
无效打印值(抽象指针p)
{
//将打印123或“abc”
std::cout
struct abstract
{
虚拟字符串get()常量=0;
};
使用抽象指针=std::shared\u ptr;
结构具体内容:公共摘要
{
字符串get()常量重写{return“123”;}
};
结构具体字符串:公共摘要
{
字符串get()常量重写{return“abc”;}
};
抽象指针工厂()
{
//这里有一些逻辑来决定返回什么具体类型
返回。。。;
}
无效打印值(抽象指针p)
{
//将打印123或“abc”

STD::CUT

如果您打算引入新的关键字作为令牌,同时使用泛型智能指针来访问所有令牌,那么有必要“令牌::())返回一些基本上足以被称为“令牌::()”的代码所理解的东西。 如果您正在通过“get()”打印(使用“cout”)令牌,并且如果某个具体令牌返回了一个对象,那么“cout”将无法理解该对象是什么或如何打印该对象

在这种情况下,将所有标记转换为某种常见的基本类型(如“Cheers and hth.-Alf”建议的“char*”或“string”)似乎很好

此外,如果打印是一项要求,那么可以将以下函数添加到抽象类中:

virtual void token::print(ostream &);

通过这种方式,每个具体的对象都会自动打印。

每当我需要这样的内容时,我就求助于CRTP。然而,即使是CRTP也允许抽象(非模板化)基类,以便更容易地传递这些。我在我的中大量使用了这种方法。可能是检查Boost.TypeErasure?抽象对象不能简单地支持访问吗?不了解用例就很难理解需求。在我看来,在不需要访问的情况下,你太难使用复杂的模板fu了它。如果您想要的是打印某些内容的能力,那么在对象上使用print方法并根据需要重写它,或者使用to_string方法,会容易得多。@AaronI它不仅仅用于打印。用用例更新了我的问题。不应该
get()
concrete_int
中,返回
int
而不是
字符串
?确实很简单,但不完全是我想要的…:)我会记住它作为一种替代方法,我们会看到它最终的结果。:)
virtual void token::print(ostream &);