C ++ 17 сделать функцию, возвращающую шаблон типа, затем написать реализацию для поддерживаемых типов - PullRequest
1 голос
/ 15 апреля 2020

Я хотел бы преобразовать следующий пример кода

class Example{
public:
    float getFloat(){return 0;}
    int getInt(){return 0;};
    std::vector<float> getFloatVector(){
        return std::vector<float>();
    }
};

в код с немного лучшим синтаксисом - например, он должен выглядеть так:

class Example2 {
    public:
        template <class T> virtual T get();
    };
    Example2::get<float>(){
        return 0;
    }
    Example2::get<int>(){
        return 0;
    }
    Example2::get<std::vector<float>>(){
        return std::vector<float>();
    }

Конечно, второй пример кода не компилируется, но показывает, как я хотел бы использовать Пример класса:

Example2 example;
LOGD("%d",example.get<float>());

1 Ответ

2 голосов
/ 15 апреля 2020

Шаблон функции-члена не может быть объявлен как virtual, поэтому вы можете изменить объявление основного шаблона на

class Example2 {
public:
    template <class T> T get();
};

, а затем специализировать его как

template <>
float Example2::get<float>(){
    return 0;
}
template <>
int Example2::get<int>(){
    return 0;
}
template <>
std::vector<float> Example2::get<std::vector<float>>(){
    return std::vector<float>();
}

, так как C ++ 17 мы можем использовать constexpr, если как

class Example2 {
public:
    template <class T> T get();
};

template <typename T>
T Example2::get() {
    if constexpr (std::is_same_v<T, float>) 
        return 0;
    else if constexpr (std::is_same_v<T, int>) 
        return 0;
    else if constexpr (std::is_same_v<T, std::vector<float>>) 
        return std::vector<float>();
    else
        return ...;
}
...