有没有办法在非模板类中定义模板成员? #2 [英] Is there a way to define a template member in a non-template class? #2
问题描述
我有一个模板类 class_A
:
// class_A.h
#pragma once
#include <iostream>
#include <tuple>
template <class T>
class class_A
{
public:
class_A(){}
T Function_A(T parameter)
{
return parameter;
}
};
我正尝试在非模板类 class_B
作为私有成员:
that I am trying to use in a non-template class class_B
as private member:
// class_B.h
#pragma once
#include <tuple>
#include <iostream>
#include "class_A.h"
class class_B
{
public:
class_B();
template <typename T> T Evaluate(T parameter);
private:
std::tuple<class_A<double>, class_A<char> > As;
};
和
// class_B.cc
#include "class_B.h"
class_B::class_B(){}
template <typename T>
T class_B::Evaluate(T parameter)
{
return std::get<class_A<T>>(As).Function_A(parameter); //This is causing error
//return parameter // This works
}
template double class_B::Evaluate(double parameter);
template char class_B::Evaluate(char parameter);
和我的 main.cc
是:
// main.cc
#include<iostream>
#include <string>
#include "class_B.h"
using namespace std;
int main()
{
class_B B;
std::cout<< B.Evaluate(5.2) <<std::endl;
std::cout << B.Evaluate('h') << std::endl;
return 0;
}
我收到以下错误:
src/class_B.cc:8:12: error: no matching function for call to 'get'
return std::get<class_A<T>>(As).Evaluate(parameter);
.
.
.
etc.
这是对答案的尝试:https://stackoverflow.com/a/55357742/9203360 无效,但如果可行,则非常理想。
This is a trial of the answer: https://stackoverflow.com/a/55357742/9203360 that didn't work, but would be ideal if it did.
推荐答案
正如我在评论中提到的, std :: get $ c $的重载c>以类型作为模板参数并返回该类型的元组元素仅在C ++ 14起可用。
As I mentioned in the comments, the overload of std::get
taking a type as template argument and returning the tuple element of that type is available only since C++14.
根据您的评论,您并未针对C +进行编译+14或更高版本,因此没有匹配类型为第一个模板参数的 std :: get
。
Per your comment you were not compiling against C++14 or later and so there was no match for std::get
with a type as first template argument.
这篇关于有没有办法在非模板类中定义模板成员? #2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!