C++中的模板机制只是偶然地对模板元编程有用.另一方面,D's专门设计用于促进这一点.而且显然它更容易理解(或者我听说过).
我没有D的经验,但是我很好奇,你能用D做什么,而你在模板元编程方面不能用C++做什么?
可以在编译时定义静态数组,如下所示:
const std::size_t size = 5;
unsigned int list[size] = { 1, 2, 3, 4, 5 };
Run Code Online (Sandbox Code Playgroud)
问题1 - 是否可以通过使用各种元编程技术在编译时"以编程方式"分配这些值?
问题2 - 假设数组中的所有值都是相同的barr,是否可以在编译时以编程方式选择性地分配值?
例如:
const std::size_t size = 7;
unsigned int list[size] = { 0, 0, 2, 3, 0, 0, 0 };
Run Code Online (Sandbox Code Playgroud)
更新: Georg Fritzsche的解决方案非常棒,需要一些工作才能在msvc和intel编译器上进行编译,但这仍然是解决问题的一种非常有趣的方法.
我定义了自己的自定义注释
@Target(value={ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyCustomAnnotation {
Class<?> myType();
}
Run Code Online (Sandbox Code Playgroud)
如何,如果有的话,我可以使属性可选
出于内省的目的,有时我想自动为类型或类似的东西分配序列号.
不幸的是,模板元编程本质上是一种功能语言,因此缺乏实现这种计数器的全局变量或可修改状态.
或者是吗?
按请求的示例代码:
#include <iostream>
int const a = counter_read;
counter_inc;
counter_inc;
counter_inc;
counter_inc;
counter_inc;
int const b = counter_read;
int main() {
std::cout << a << ' ' << b << '\n'; // print "0 5"
counter_inc_t();
counter_inc_t();
counter_inc_t();
std::cout << counter_read << '\n'; // print "8"
struct {
counter_inc_t d1;
char x[ counter_read ];
counter_inc_t d2;
char y[ counter_read ];
} ls;
std::cout << sizeof ls.x << ' ' << sizeof ls.y << '\n'; // print "9 …Run Code Online (Sandbox Code Playgroud) 我正在尝试编写一个装饰器来做日志记录:
def logger(myFunc):
def new(*args, **keyargs):
print 'Entering %s.%s' % (myFunc.im_class.__name__, myFunc.__name__)
return myFunc(*args, **keyargs)
return new
class C(object):
@logger
def f():
pass
C().f()
Run Code Online (Sandbox Code Playgroud)
我想要打印:
Entering C.f
Run Code Online (Sandbox Code Playgroud)
但我收到此错误消息:
AttributeError: 'function' object has no attribute 'im_class'
Run Code Online (Sandbox Code Playgroud)
据推测,这与'logger'中'myFunc'的范围有关,但我不知道是什么.
如果我定义一个小python程序
class a():
def _func(self):
return "asdf"
# Not sure what to resplace __init__ with so that a.func will return asdf
def __init__(self, *args, **kwargs):
setattr(self, 'func', classmethod(self._func))
if __name__ == "__main__":
a.func
Run Code Online (Sandbox Code Playgroud)
我收到回溯错误
Traceback (most recent call last):
File "setattr_static.py", line 9, in <module>
a.func
AttributeError: class a has no attribute 'func'
Run Code Online (Sandbox Code Playgroud)
我想弄清楚的是,如何在不实例化对象的情况下动态地将类方法设置为类?
这个问题的答案是
class a():
pass
def func(cls, some_other_argument):
return some_other_argument
setattr(a, 'func', classmethod(func))
if __name__ == "__main__":
print(a.func)
print(a.func("asdf"))
Run Code Online (Sandbox Code Playgroud)
返回以下输出
<bound method type.func of <class '__main__.a'>> …Run Code Online (Sandbox Code Playgroud) 我想知道在使用模板元编程技术时使用静态const和枚举黑客有什么区别.
EX :(斐波那契通过TMP)
template< int n > struct TMPFib {
static const int val =
TMPFib< n-1 >::val + TMPFib< n-2 >::val;
};
template<> struct TMPFib< 1 > {
static const int val = 1;
};
template<> struct TMPFib< 0 > {
static const int val = 0;
};
Run Code Online (Sandbox Code Playgroud)
与
template< int n > struct TMPFib {
enum {
val = TMPFib< n-1 >::val + TMPFib< n-2 >::val
};
};
template<> struct TMPFib< 1 > {
enum { val = …Run Code Online (Sandbox Code Playgroud) 您可以为类动态定义类方法,如下所示:
class Foo
end
bar = %q{def bar() "bar!" end}
Foo.instance_eval(bar)
Run Code Online (Sandbox Code Playgroud)
但是你如何做相反的事情:删除/取消定义一个类方法?我怀疑Module remove_method和undef_method方法可能可以用于此目的,但我在谷歌搜索几个小时之后看到的所有示例都是用于删除/取消定义实例方法,而不是类方法.或者也许你可以传递一种语法instance_eval来做到这一点.
提前致谢.
我有一组名为的可交换二进制函数的重载overlap,它接受两种不同的类型:
class A a; class B b;
bool overlap(A, B);
bool overlap(B, A);
Run Code Online (Sandbox Code Playgroud)
overlap当且仅当一个形状与另一个形状重叠时,我的函数返回true - 这是讨论multimethods时使用的一个常见示例.
因为overlap(a, b)相当于overlap(b, a),我只需要实现关系的一个"侧".一个重复的解决方案是写这样的东西:
bool overlap(A a, B b) { /* check for overlap */ }
bool overlap(B b, A a) { return overlap(a, b); }
Run Code Online (Sandbox Code Playgroud)
但我宁愿不N! / 2使用模板生成相同功能的额外简单版本.
template <typename T, typename U>
bool overlap(T&& t, U&& u)
{ return overlap(std::forward<U>(u), std::forward<T>(t)); }
Run Code Online (Sandbox Code Playgroud)
不幸的是,这很容易无限递归,这是不可接受的:见 http://coliru.stacked-crooked.com/a/20851835593bd557
如何防止这种无限递归?我正确地解决了这个问题吗?
method_missing在Ruby中定义方法时有什么需要注意的吗?我想知道是否存在一些不那么明显的继承,异常抛出,性能或其他任何东西的交互.
metaprogramming ×10
c++ ×5
templates ×3
python ×2
ruby ×2
annotations ×1
class ×1
d ×1
java ×1
reflection ×1
setattr ×1
state ×1
static-array ×1