一种在模板类中返回模板变量的方法?

时间:2018-07-19 15:33:12

标签: c++ templates debugging

这是简单的代码:

#include <iostream>
using namespace std;

template <class T>
class A
{
  public:
    A(T& arg): value(arg) {};

    template <typename U>
    U foo(bool check)
    {
      U a;

      if(check)
      {
        char ex = 'x';
        a = ex;
        return a;
      }

      else
      {
        a = value;
        return value;
      }
    }

  private:
     T value;

};

int main()
{
  int b = 5;
  A <int>a1(b);

  cout <<a1.foo(true) << endl;

  return 0;
}

我收到此错误:

main.cpp: In function 'int main()':
main.cpp:39:21: error: no matching function for call to 'A<int>::foo(bool)'
   cout <<a1.foo(true) << endl;
                     ^
main.cpp:11:7: note: candidate: 'template<class U> U A<T>::foo(bool) [with U = U; T = int]'
     U foo(bool check)
       ^~~
main.cpp:11:7: note:   template argument deduction/substitution failed:
main.cpp:39:21: note:   couldn't deduce template parameter 'U'
   cout <<a1.foo(true) << endl;

当我在类中明确声明它时,它找不到函数。我试图将其转换为所需的格式。它仍然给我错误。

我是模板的新手。我要去哪里错了?请不要只修复我的代码。向我解释一下您的详细更改。

修改: 感谢您的回答。我有人问我为什么要问这个问题。这里还有更多背景信息,

我正在尝试制作一个定制的数组,该数组可以接受从标准数据类型到数组和对象的任何数据类型。该数组索引从1开始。但是,第零个元素是一个无符号整数,具有此数组中元素的数量。我有一个称为“ GetElementAt”的函数,它将在某个索引处获取元素。我现在遇到的问题是,如果元素编号为0,我希望此函数返回一个无符号整数(元素数量),并返回数据类型T(数组中包含数据的元素之一)否则,请输入T)。

3 个答案:

答案 0 :(得分:2)

foo是模板类中的方法模板。因此,您必须为a1定义模板参数时,也必须为foo指定模板参数:

a1.foo<char>(true);

答案 1 :(得分:2)

模板参数推导不能在返回类型上完成。您需要指定模板参数

a1.foo<int>(true) // if U needs to be an int

或使用类中的T,您正在对类型UT的变量进行赋值,因此可能正是您所需要的。

   template <class T>
    class A
    {
      public:
        A(T& arg): value(arg) {};

        T foo(bool check)
        {
            // ...
        }

        // or alternatively:
        template <typename U = T>
        U foo(bool check)
        {
            // ...
        }

      private:
         T value;

};

答案 2 :(得分:1)

我想你想要

template <class T>
class A
{
public:
    A(const T& arg): value(arg) {};

    template <bool check>
    auto foo()
    {
        if constexpr (check) {
            return 'x'; // char
        } else {
           return value; // T
        }
    }

private:
    T value;
};

使用方式:

std::cout << a1.foo<true>() << endl;  // x
std::cout << a1.foo<false>() << endl; // 5