使用模板在类中声明新功能

时间:2019-03-26 20:33:59

标签: c++ class templates

我还在学习模板。我不确定是否可以使用模板在类(方法)内声明/(自动定义)函数。也就是说,我有一个这样定义的功能模板,例如:

template<typename T>
T getT() {
    T result;
    return result;
}

还有一个我想要基于模板创建“新函数”的类,如下所示:

class World{
public:
    World();
    ~World();
    getT<int>; //"Magically" create new function from the template (return type 'int')

}

我真正想要的是在World中仅具有特定给定类型的方法。这意味着当我想“神奇地”基于模板创建方法时,我想将模板函数复制粘贴到类中,但是具有给定类型。

例如:

class World{
public:
    World();
    ~World();

    //The magically created function with T equal to int
    int getT(){
        int result;
        return result;
    }

}

然后我当然希望能够调用该函数:

int main(){
    World world; //Create world object
    world.getT<int>; //Call the function
    return 0;
}

即使在这里我说我会用getT<int>来称呼它,也可能只是getT()(如果它是模板函数的完美复制粘贴)。

2 个答案:

答案 0 :(得分:0)

getT<int>; //"Magically" create new function from the template (return type 'int')

我认为那不行。

似乎您希望能够使用宏扩展之类的模板。不幸的是,它们是完全不同的东西,模板不能像宏扩展那样工作。

但是,您可以使用类似以下的内容:

template<typename T>
struct GetHelper
{
   T get()
   {
      return T{};
   }
};


class World : private GetHelper<int>,
              private GetHelper<double>
{
   public:
      World() {}
      ~World() {}
      template <typename T>
         get()
         {
            return static_cast<GetHelper<T>*>(this)->get();
         }

};

现在您可以使用:

World w;
int a = w.get<int>();
double b = w.get<double>();

您也可以将GetHelper隐藏为private类型的World

class World 
{
   private:
      template<typename T>
         struct GetHelper
         {
            T get()
            {
               return T{};
            }
         };

      struct Data : GetHelper<int>,
                    GetHelper<double>{};

      Data data;

   public:
      World() {}
      ~World() {}
      template <typename T>
         get()
         {
            return static_cast<GetHelper<T>*>(&data)->get();
         }

};

答案 1 :(得分:0)

变得饱满

template<typename T>
T& getT() {
    T result;
    return result;
}

将返回对临时目录的引用。请做

template<typename T>
T getT() {
    T result;
    return result;
}

不带“&”

如果只是为了获得特定成员,则可以使用std :: tuple。

https://en.cppreference.com/w/cpp/utility/tuple/get