以下代码工作正常:
template<typename T>
struct Wrap {};
template<template <class> class OUT, typename IN>
void Extract (OUT<IN> *obj)
{ /* only class 'IN' is used in some way */ }
int main ()
{
Wrap<int> obj;
Extract(&obj);
}
但是,我传递一个指针参数来提取外部类型和内部类型。
有没有更好的方法可以通过显式模板实例化来调用该方法?
提取<包裹 > ()
;
编辑:
我将详细说明我的问题。这解释了为什么像 Extract();
这样的简单答案是不可能的。
我正在为 C++ 代码编写一个文本解析器。无论解析器在哪里找到,
x = (Type) y;
它都应该转换为,
x = Extract<Type> (y);
现在,类型可以是
- 任何普通类型,例如
int*
或 A**
- 一些模板化模板,例如
Wrap A>
现在,Extract()
对于这两种情况的工作方式有所不同。我必须弄清楚使用模板,无论是 Extract
还是 Extract >
。
==>用更简单的语言来说,可以调用该方法:
-
Extract()
-
Extract; >()
我可以判断它是否在第一种情况下被调用,但是我如何判断它是否在第二种情况下被调用? (前提是,我也想知道内部类型)。
Following code works fine:
template<typename T>
struct Wrap {};
template<template <class> class OUT, typename IN>
void Extract (OUT<IN> *obj)
{ /* only class 'IN' is used in some way */ }
int main ()
{
Wrap<int> obj;
Extract(&obj);
}
But, I am passing a pointer argument to extract the outer type and inner type.
Is there any better way by which I can invoke the method with explicit template instantiation ?
Extract<Wrap<int> > ()
;
Edit:
I will detail my question a bit more. This explains, why the easy answer like Extract<Wrap, int>();
is not possible.
I am writing a text parser, for C++ code. Wherever, parser finds,
x = (Type) y;
it should convert into,
x = Extract<Type> (y);
Now, the Type can be
- any normal type like,
int*
or A**
- some templatized template like
Wrap<A>
Now, Extract()
works different for both the cases. I have to figure out using template that, whether it's Extract<int*>
or Extract<Wrap<int> >
.
==> In simpler language, the method can be called:
Extract<int*>()
Extract<Wrap<int> >()
I can figure out if it's called in 1st case, but how can I figure out if it's called in 2nd case ? (provided that, I want to know internal type also).
发布评论
评论(2)
Extract 怎么样? (&obj);
?但为什么要明确指定它呢?大多数时候,为了简单起见,您宁愿让编译器自动为您推断类型。
编辑:您是否考虑过专门从事
Wrap
?如果需要,您还可以添加
T*
的专业化。How about
Extract<Wrap, int> (&obj);
?But why do you want to specify it explicitly? Most of the time you'd rather have the compiler deduce the types for you automatically for simplicity.
EDIT: Have you considered just specializing for
Wrap<U>
?If needed you can add a specialization for
T*
as well.这很好用
你肯定缺乏对 C++ 模板的基本了解。阅读C++ 模板 - 完整指南一书。
This works fine
You certainly lack basic understanding of C++ templates. Read the book C++ Templates - The Complete Guide.