c++ - 我可以存储类型名称吗?

标签 c++

这是我访问内存的示例类:

class memory {
  public:
    memory();

    template <typename T>
    T get(int index);
    template <typename T>
    void set(int index, T value);
};

我在这里使用它:

int main(){
  memory mem;

  float f = mem.get<float>(0);
  char* str = mem.get<char*>(1);

  mem.set<float>(0, 25);  // int passed, upgraded to float

  return 0;
}

我想这样使用它:

int main(){
  memory<float, char*> mem;  // typenames defined only once. Must accept a variable number of template arguments

  float f = mem.get(0);
  char* str = mem.get(1);

  mem.set(0, 25);  // int passed, upgraded to float

  return 0;
}

我该如何实现?有可能吗?

最佳答案

你似乎想要 std::tuplehana::tuple。完全有可能改变你的类,这样你就不需要每次都发送类型。

但是,您仍然需要将一些内容作为模板参数传递。通常,变量的索引或类型的索引就足够了。

标准库中的 tuple 类是这样的:

std::tuple<int, std::string> tup;

std::get<0>(tup) = 5; // assign the int
std::get<1>(tup) = "test"; // assign the string

Boost hana 以类似的方式运行它,但使用 operator[]:

hana::tuple<int, std::string> tup;

tup[0_c] = 5; // assign the int
tup[1_c] = "test"; // assign the string

_c 是用户提供的文字,将 int 转换为整数常量,因此可以在编译时使用该值。


那么你会怎么做呢?

只需将您的 int 参数更改为模板参数:

int main() {
  memory<float, char*> mem;

  float f = mem.get<0>();
  char* str = mem.get<1>();

  mem.set<0>(25);  // int passed, upgraded to float

  return 0;
}

然后,根据索引推断类型是什么,使用这样的东西:

template<std::size_t, typename>
struct memory_element; // no basic case

// In this case, we pass a number and a memory class
// We extend the case were the index is decremented, and we remove the first type.
template<std::size_t index, typename Head, typename... Tail>
struct memory_element<index, memory<Head, Tail...> : memory_element<index - 1, memory<Tail...>> {};

// Case where we get to 0
template<typename T, typename... Rest>
struct memory_element<0, memory<T, Rest...>> {
    using type = T;
};

// Alias for ease of use
template<std::size_t I, typename M>
using memory_element_t = typename memory_element<I, M>::type;

你可以像这样使用它:

int main () {
    // T1 is int
    using T1 = memory_element_t<0, memory<int, float>>;

    // T2 is float
    using T2 = memory_element_t<1, memory<int, float>>;
}

关于c++ - 我可以存储类型名称吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45532849/

相关文章:

c# - 从 C# 调用带有 C++ header 的 dll

c++ - 警告: 'LPEVENT CItem::m_pkExpireEvent' and warning:format '%d' expects type 'int' , but argument 3 has type 'double'

c++ - kruskal算法实现

c# - 如何从 C# 返回集合对象并在 C++ 中访问它们?

c++ - Cuda 类型双关语 - memcpy vs UB union

c++ - lldb/Xcode : how to print thread index, id 或名称?

c++ - 什么是 undefined reference /未解析的外部符号错误,我该如何解决?

c++ - 我面对这个 : invalid types `double[int]' for array subscript in my program

c++ - 使用带有仅 header 库的 Find*.cmake 文件

c++ - 为什么叫 bool casting?